package com.joeyzh.utils;

import android.os.AsyncTask;
import android.text.TextUtils;


import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 自定义列表中查询搜索的工具类
 *
 * @param <E>
 */
public abstract class ModelFilter<E extends Object> extends AsyncTask<String, Integer, List<E>> {

    private List<E> original;
    private OnFilterListener filterListener;
    private String[] specialChars = {"(", ")"};
    private List<String> equalKeys = new ArrayList<>();

    public ModelFilter(List<E> original, OnFilterListener filterListener) {
        this.original = original;
        this.filterListener = filterListener;
    }

    public void addMatcher(String key) {
        equalKeys.add(key);
    }

    public boolean equals(Pattern pattern, E item) {
        for (String key : equalKeys) {
            Matcher matcher = pattern.matcher(new ModelGetSetUtil<E>(item).getValue(key).toString());
            if (matcher.find()) {
                return true;
            }
            continue;
        }
        return false;
    }

    @Override
    protected List<E> doInBackground(String... params) {
        List<E> results = new ArrayList<>();
        String key = params[0].trim();
        if (TextUtils.isEmpty(key)) {
            return original;
        }
        key = clearSpecialChars(key);
        try {
            Pattern pattern = Pattern.compile(key, Pattern.CASE_INSENSITIVE);
            for (int i = 0; i < original.size(); i++) {
                if (equals(pattern, original.get(i))) {
                    results.add(original.get(i));
                }

            }
        } catch (Exception e) {

        }
        return results;
    }

    @Override
    protected void onPostExecute(List<E> results) {
        super.onPostExecute(results);
        if (filterListener != null) {
            filterListener.onFilterResult(results);
        }
    }

    private String clearSpecialChars(String key) {
        for (int i = 0; i < specialChars.length; i++) {
            String s = specialChars[i];
            int index = key.indexOf(s);
            if (index > 0) {
                key = key.substring(0, index);
            }
        }
        return key;
    }

    /**
     * 列表搜索结果方法
     *
     * @param <E>
     */
    public interface OnFilterListener<E> {
        /**
         * 搜索结果回调
         *
         * @param results
         */
        void onFilterResult(List<E> results);
    }
}

